package com.zero.xiaodai.utils;





import java.util.ArrayList;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoDB {
	
	private  static MongoClient mongo = null;   
	
	private  static MongoClient mongo2=null;
	
    private MongoDB() {
    }
    /**
     * 根据名称获取DB，相当于是连接
     * 
     * @param dbName
     * @return
     */
    public static DB getDB(String dbName) {
        if (mongo == null) {
            // 初始化
            init();
        }
        return new DB(mongo, dbName);
    } 
   
    /**
     * 初始化连接池，设置参数。
     */
    private static void init() {
        // 其他参数根据实际情况进行添加
    	 	ServerAddress serverAddress = new ServerAddress(MongoProperties.MONGO_HOST, MongoProperties.MONGO_PORT);  
            List<ServerAddress> seeds = new ArrayList<ServerAddress>();  
            seeds.add(serverAddress);  
            
            MongoCredential credentials = MongoCredential.createCredential(MongoProperties.MONGO_USERNAME, MongoProperties.DB_NAME,
    	    		MongoProperties.MONGO_PASSWORD.toCharArray());
            
            /*
    	    MongoCredential credentials = MongoCredential.createMongoCRCredential(MongoProperties.MONGO_USERNAME, MongoProperties.DB_NAME,
    	    		MongoProperties.MONGO_PASSWORD.toCharArray());      
    	    */
    	    
            List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();  
            credentialsList.add(credentials);  
            mongo = new MongoClient(seeds, credentialsList);         
            MongoClientOptions.builder(mongo.getMongoClientOptions())
            		.connectionsPerHost(MongoProperties.PERHOST_SIZE)
            		.socketKeepAlive(MongoProperties.ISKEEPLIVE)
            		.connectTimeout(MongoProperties.CONNECT_TIMEOUT)
            		.socketTimeout(MongoProperties.SOCKET_TIMEOUT)
            		.maxWaitTime(MongoProperties.MAXWAIT_TIME)           		
            		.threadsAllowedToBlockForConnectionMultiplier(MongoProperties.THREADSALLOWEDTOBLOCKFORCONNECTIONMULTIPLIER);
            
//            mongo = new MongoClient(MONGO_HOST,MONGO_PORT );           
//            MongoClientOptions.builder(mongo.getMongoClientOptions())
//            		.connectionsPerHost(PERHOST_SIZE)
//            		.socketKeepAlive(ISKEEPLIVE)
//            		.connectTimeout(CONNECT_TIMEOUT)
//            		.socketTimeout(SOCKET_TIMEOUT)
//            		.maxWaitTime(MAXWAIT_TIME)
//            		.threadsAllowedToBlockForConnectionMultiplier(THREADSALLOWEDTOBLOCKFORCONNECTIONMULTIPLIER);
        
    }
    
  

}
